#include "OpenGLContext.h"
#include "GL\glew.h"

using System::Windows::Forms::ControlStyles;
using System::IntPtr;
using System::Exception;

OpenGLContext::OpenGLContext()
{
	//
}

void OpenGLContext::OnHandleCreated(System::EventArgs^ e)
{
	InitGL();
	OnInitialized();
}

void OpenGLContext::InitGL()
{
	_device = GetDC((HWND) this->Handle.ToPointer());

	if (_device == NULL) {
		throw gcnew Exception(L"Failed to retrieve device context");
	}

	static PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		16,										    // Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};

	int pixelFormat; 
	if((pixelFormat = ::ChoosePixelFormat(_device, &pfd)) == 0) {
		throw gcnew Exception(L"ChoosePixelFormat Failed");
	}

	if(::SetPixelFormat(_device, pixelFormat, &pfd) == FALSE) {
		throw gcnew Exception(L"SetPixelFormat Failed");
	}

	if((_context = ::wglCreateContext(_device)) == NULL) {
		throw gcnew Exception(L"wglCreateContext Failed");
	}

	if((::wglMakeCurrent(_device, _context)) == NULL) {
		throw gcnew Exception(L"wglMakeCurrent Failed");
	}

	::glewInit();
}


